//: Playground - noun: a place where people can play

import UIKit

// 归并排序
func mergeSort(_ array: [Int]) -> [Int] {
    var helper = Array.init(repeating: 0, count: array.count);
    var array = array;
    print("helper - \(helper)");
    mergeSort(&array, &helper, 0, array.count - 1);
    return array;
}

func mergeSort(_ array: inout [Int], _ helper: inout [Int], _ low: Int, _ high: Int) {
    guard low < high else {
        return;
    }
    
    let middle = (high - low) / 2 + low;
    mergeSort(&array, &helper, low, middle);
    mergeSort(&array, &helper, middle + 1, high);
    merge(array: &array, &helper, low, middle, high);
}

func merge(array: inout [Int], _ helper: inout [Int], _ low: Int, _ middle: Int, _ high: Int) {
    // copy both halves into a helper array
    for i in low...high {
        helper[i] = array[i];
    }
    
    var helperLeft = low, helperRight = middle + 1, current = low;
    
    // iterate through helper array and copy the right one to original array while helperLeft <= middle && helperRight <= high
    while helperLeft <= middle && helperRight <= high {
        if helper[helperLeft] <= helper[helperRight] {
            array[current] = helper[helperLeft];
            helperLeft = helperLeft + 1;
        } else {
            array[current] = helper[helperRight];
            helperRight = helperRight + 1;
        }
        
        current += 1;
    }
    
    // handle the rest
    guard middle - helperLeft >= 0 else {
        return;
    }
    
    for i in 0...middle - helperLeft {
        array[current + i] = helper[helperLeft + i];
    }
}

let beforeArray = [5,4,3,2,1];
let afterArray = mergeSort(beforeArray);

let arrayA = [1,2,3];
let arrayB = arrayA;
print("arrayA: \(arrayA) - arrayB: \(arrayB)");


func add(_ num: Int) -> (Int) -> Int {
    return { val in
        return num + val;
    }
}

let addTwo = add(2);
addTwo(4);

let a = (0...10).map { $0 * $0 }.filter { $0 % 2 == 0 }
print("\(a)");
